package com.itheima.reggie.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.Service.UserService;
import com.itheima.reggie.exception.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.utils.MessageController;
import com.itheima.reggie.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session)
    {
String phone4=user.getPhone();
if(phone4!=null)
{
    String code= ValidateCodeUtils.generateValidateCode(4).toString();
//   MessageController.ta(phone4,code);
  session.setAttribute("phone4","1234");
    System.out.println(code);
    return R.success("手机验证码短信发送成功");
}
 return R.error("短信发送失败");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session)//这里之所以不用User对象来接收是因为他没有code属性
    {
      //获取手机号
       String phone= map.get("phone").toString();
       //获取验证码
        String code1=map.get("code").toString();
        //从session获取session验证码
        Object code2=session.getAttribute("phone4");
        //进行验证码比较
        if(code2!=null&&code2.equals(code1))
        {
            //如果比对成功就成功登录
            //判断用户是不是新用户，如果是新用户自动创建

            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("phone",phone);
            User user=userService.getOne(queryWrapper);
            if(user==null)
            {
                 user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);

            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }

return R.error("登录失败,验证码错误");
    }
}
